package com.bolingcavalry.crm.minio.service;

import io.minio.*;
import io.minio.errors.*;
import io.minio.http.Method;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class MinioService {

    @Autowired
    private MinioClient minioClient;

    @Value("${minio.bucketName}")
    private String bucketName;

    @Value("${minio.endpoint}")
    private String endpoint;

    //通用上传文件方法，只返回文件名
    public String uploadFile(MultipartFile file) throws Exception {
        String objectName = System.currentTimeMillis() + "-" + file.getOriginalFilename();

        // 判断桶是否存在
        boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        if (!found) {
            // 创建桶
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        }

        // 上传文件
        minioClient.putObject(
                PutObjectArgs.builder()
                        .bucket(bucketName)
                        .object(objectName)
                        .stream(file.getInputStream(), file.getSize(), -1)
                        .contentType(file.getContentType())
                        .build());
        // 返回文件URL
        endpoint="https://crm.ceebic.net/minio";
        String s = endpoint + "/" + bucketName + "/" + objectName;
        return s;
        //只返回文件名
        //return objectName;
    }

    // 生成预签名的 URL，有效期为 7 天
    @SneakyThrows
    public List<String> getPresignedUrl(List<String> objectNames) {
        List<String> urls = new ArrayList<>();
        for (String objectName : objectNames) {
            String url = minioClient.getPresignedObjectUrl(
                    GetPresignedObjectUrlArgs.builder()
                            .method(Method.GET)
                            .bucket(bucketName)
                            .object(objectName)
                            .expiry(7, TimeUnit.DAYS)
                            .build());
            // 将HTTP URL转换为自定义HTTPS URL
            if (url.startsWith("http://")) {
                // 替换协议为HTTPS
                url = url.replaceFirst("^http://", "https://");
                // 替换域名为自定义域名
                url = url.replaceFirst("121.40.72.209:9004", "crm.ceebic.net/minio");
            }
            urls.add(url);
        }
        return urls;
    }
    @SneakyThrows
    public String getPresignedUrl(String objectName) {
        String url = minioClient.getPresignedObjectUrl(
                GetPresignedObjectUrlArgs.builder()
                        .method(Method.GET)
                        .bucket(bucketName)
                        .object(objectName)
                        .expiry(7, TimeUnit.DAYS)
                        .build());
        // 将HTTP URL转换为自定义HTTPS URL
        if (url.startsWith("http://")) {
            // 替换协议为HTTPS
            url = url.replaceFirst("^http://", "https://");
            // 替换域名为自定义域名
            url = url.replaceFirst("121.40.72.209:9004", "crm.ceebic.net/minio");
        }

        return url;
    }

    public String deleteFile(String objectName) throws Exception {
        minioClient.removeObject(
                RemoveObjectArgs.builder()
                        .bucket(bucketName)
                        .object(objectName)  // 就是你的文件名（含路径）
                        .build()
        );
        return "删除成功";
    }
}